package com.atguigu.guli.service.base.handler;

import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice//用来监控controller的方法是否有异常,如果有异常会被当前类去处理
public class GlobalExceptionHandler {

//    异常处理方法:ExceptionHandler 指定要处理的异常
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public R error(Exception e){//形参的异常类型必须和处理的异常类型一样
//        e.printStackTrace();
        log.info("异常"+ ExceptionUtils.getStackTrace(e));
        return R.error();
    }

    @ResponseBody
    @ExceptionHandler(GuliException.class)
    public R error(GuliException e){//形参的异常类型必须和处理的异常类型一样
//        e.printStackTrace();
        log.info("异常"+ ExceptionUtils.getStackTrace(e));
        return R.error().message(e.getMessage()).code(e.getCode());
    }

//    捕获指定类型异常
    @ResponseBody
    @ExceptionHandler(BadSqlGrammarException.class)
    public R error(BadSqlGrammarException e){
//        e.printStackTrace();
        log.info("异常"+ ExceptionUtils.getStackTrace(e));
        return R.setResult(ResultCodeEnum.BAD_SQL_GRAMMAR);
    }
    //    捕获指定类型异常
    @ResponseBody
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R error(HttpMessageNotReadableException e){
//        e.printStackTrace();
        log.info("异常"+ ExceptionUtils.getStackTrace(e));
        return R.setResult(ResultCodeEnum.JSON_PARSE_ERROR);
    }

    //    捕获指定类型异常
    @ResponseBody
    @ExceptionHandler(DuplicateKeyException.class)
    public R error(DuplicateKeyException e){
//        e.printStackTrace();
        log.info("异常"+ ExceptionUtils.getStackTrace(e));
        return R.setResult(ResultCodeEnum.DUPLICATE_KEY_ERROR);
    }
}
